import './index.less';
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import Drawer, { type DrawerProps } from '@mui/material/Drawer';
import clsx from 'clsx';
import { useAppStore } from '@/stores';
import { useControlledState } from '@/hooks';
import type { IIconImageRecord } from '../map-kit';

export type IIconLibraryProps = Omit<DrawerProps, 'onClose'> & {
  onOpenChange?: (open?: boolean) => void;
};

export type IIconLibraryRef = {
  setOpen: (open: boolean) => void;
};

export type IIconOutlineProps = {
  style?: React.CSSProperties & { '--width': string; '--height': string };
  className?: string;
  onChange?: (value?: IIconImageRecord) => void;
  value?: IIconImageRecord;
  selectedIconImage?: string;
};

export const IconOutline = (props: IIconOutlineProps) => {
  const map = useAppStore.use.map()!;
  const { style, className, selectedIconImage } = props;
  const [value, onChange] = useControlledState(props.value, props.onChange);

  const onClick = (item: IIconImageRecord) => {
    if (item.iconImage !== value?.iconImage) onChange(item);
  };

  useEffect(() => {
    if (selectedIconImage) {
      const item = map.iconImage.getIconImageRecord(selectedIconImage);
      if (item) onClick(item);
    }
  }, [selectedIconImage]);

  return (
    <div style={style} className={clsx('smap-icon-library-outline', className)}>
      {map.iconImage.iconImageList.map((item) => (
        <div
          key={item.iconImage}
          dangerouslySetInnerHTML={{ __html: item.svgStr }}
          className={clsx({ active: value?.iconImage === item.iconImage })}
          onClick={() => onClick(item)}
        />
      ))}
    </div>
  );
};

export const IconLibrary = forwardRef<IIconLibraryRef, IIconLibraryProps>((props: IIconLibraryProps, ref) => {
  const { className, open: propOpen, onOpenChange, ...drawerProps } = props;
  const [open, setOpen] = useControlledState(propOpen, onOpenChange);

  useImperativeHandle(ref, () => ({
    setOpen,
  }));

  return (
    <Drawer
      anchor="right"
      open={!!open}
      {...drawerProps}
      className={clsx(className, 'smap-icon-library')}
      onClose={() => setOpen(false)}
    ></Drawer>
  );
});

export const useIconLibrary = () => {
  const ref = useRef<IIconLibraryRef>(null);
  return useMemo(
    () => ({
      iconLibraryRef: ref,
      IconLibrary: (props: Omit<IIconLibraryProps, 'open'>) => <IconLibrary {...props} ref={ref} />,
    }),
    [],
  );
};
